package com.lsl.data_bus.example.member;

import com.lsl.data_bus.example.data.DataType;
import com.lsl.data_bus.example.data.MessageData;
import com.lsl.data_bus.example.data.StartingData;
import com.lsl.data_bus.example.data.StoppingData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

/**
 * description:
 *
 * @author: liushengli
 * data: 2023/1/12
 */
public class StatusMember implements Member {
    private final int id;

    private LocalDateTime started;

    private LocalDateTime stopped;

    private static final Logger logger = LoggerFactory.getLogger(StatusMember.class);


    public StatusMember(int id) {
        this.id = id;
    }

    @Override
    public void accept(final DataType data) {
        if (data instanceof StartingData) {
            handleEvent((StartingData) data);
        } else if (data instanceof StoppingData) {
            handleEvent((StoppingData) data);
        }
    }

    private void handleEvent(StartingData data) {
        started = data.getWhen();
        logger.info("接收者 {} 监控到应用启动时间为 {}", id, started);
    }

    private void handleEvent(StoppingData data) {
        stopped = data.getWhen();
        logger.info("接收者 {} 监控到应用停止时间为 {}", id, stopped);
        logger.info("接收者 {} 发送关闭消息 ", id);
        data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id)));
    }
}
